<?php
/**
 * 响应类
 * 支持自定义header及头部缓存，同时支持xml、json格式的返回
 */
class Response {
	
	private static $result_code = array(
				'200' => 'Success',
				'400' => 'param fail',
				'401' => 'Unauthorized',
				'403' => 'Forbidden',
				'404' => 'Not Found',
				'405' => 'Method Not Allowed',
				'500' => 'Internal Server Error',
				'503' => 'Service Unavailable',
				'4000' => 'Request frequency authentication failure',
                '4001' => 'user not regist'
			);

	private static $expire_now = 0;
	private static $expire_minute = 60;
	private static $expire_hour = 3600;
	private static $expire_day = 86400;

	public static function xml($code = '200', $result = array(), $message = null, $options = array()) {
		header('Content-Type: text/xml; charset=utf-8');

		if (class_exists('SimpleXMLElement') && ($result instanceof SimpleXMLElement)) {
			$response = $result->asXML();
		} else {
			$response = strval($result);
		}
		exit($response);
	}

	public static function json($code = '200', $result = array(), $message = null, $options = array()) {
		if (array_key_exists($code, self::$result_code)) {
			$message = is_null($message) ? self::$result_code[$code] : $message;
		}
		
		$result = array('code' => $code, 'message' => $message, 'result' => $result);
		if (is_array($options)) {
			$result = array_merge($options, $result);
		}
		header('Content-Type: application/javascript; charset=utf-8');
		exit(json_encode($result));
	}

	/**
	 * 设置HTTP HEADER里的缓存时间
	 *
	 * @param int $seconds 过期时间的秒数，0为不缓存。 如果该值大于当前的Unix时间戳，则为实际过期时间
	 */
	public static function set_expire_time($seconds) {
		$now = time();
		if ($seconds > $now) {
			$seconds -= $now;
		}
		$old = self::$_expire_time;
		self::$_expire_time = intval($seconds);

		return $old;
	}
	
	/**
	 * 自定义header
	 * @param string $name
	 * @param string $value
	 */
	public static function setHeaer($name, $value) {
		header($name . ':' . $value);
	}
	
	/**
	 * 设置header过期时间
	 */
	private static function _set_expire_headers() {
		if (self::$_expire_time) {
			header('Cache-Control: max-age=' . self::$_expire_time);
			header('Expires: ' . gmdate('D, j M Y H:i:s T', time() + self::$_expire_time));
		} else {
			header("Cache-Control: no-cache, must-revalidate");
			header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
		}
	}
}